package top.i51213.fastaction.png;

import android.graphics.Bitmap;

import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.ZipOutputStream;

public class PngWriter {
    int width;
    int height;
    OutputStream out;
    OutputStream zipOut;
    public PngWriter(int width, int height, OutputStream out) throws IOException {
        this.width=width;
        this.height=height;
        this.out=out;
        writeHead();
    }
    private void writeHead() throws IOException {
        byte[] head = new byte[] {(byte) 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A };
        out.write(head);
        ChunkUtil.buildIHDR(width, height, 8, 6).writeTo(out);
        //ChunkUtil.build_sRGB().writeTo(out);
        //ChunkUtil.build_gAMA().writeTo(out);
    }
    public void addBitmap(Bitmap bitmap) throws IOException {
        int width=bitmap.getWidth();
        int height=bitmap.getHeight();

        if(bitmap.getWidth()!=width){
            throw new IOException("bitmap width !=  dest width");
        }

        if(zipOut==null){
            zipOut=new ZOutputStream(new IDATWriter(out),9);
        }
        System.out.println("单行数量"+bitmap.getRowBytes());
        System.out.println("总数量"+bitmap.getByteCount());
        int[] pixels=new int[width];
        byte[] rgbas=new byte[width*4+1];
        for (int y = 0; y < height; y++) {
            bitmap.getPixels(pixels,0,width,0,y,width,1);
            Util.argb2rgba(pixels,0,width,rgbas,1);
            zipOut.write(rgbas);
            if(y==0){
                System.out.println(Integer.toHexString(pixels[0]));
                for (int i = 0; i < 9; i++) {
                    System.out.print(Integer.toHexString(rgbas[i]&0xff)+" ");
                }
                System.out.println();
            }
        }
    }
    public void close() throws IOException {
        zipOut.close();
        ChunkUtil.BuildIEND().writeTo(out);
    }
}
